package com.yookey.common.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

/**
 * className MoneySerializer
 *
 * @Author: Zhang Shao Hui
 * @Description:
 * @Date:Create：in 2019/12/25 16:16
 * @Modified By：
 */
public class TwoDecimalSerializer extends JsonSerializer<Number> {

    private static final long ONE_HUNDRED = 100;

    @Override
    public void serialize(Number value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (value == null) {
            value = BigDecimal.ZERO;
        }
        DecimalFormat df = new DecimalFormat("0.00");
        df.setRoundingMode(RoundingMode.DOWN);
        jsonGenerator.writeNumber(df.format(BigDecimal.valueOf(value.doubleValue()).divide( new BigDecimal(ONE_HUNDRED))));
    }
}
